class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> matrix(n, vector<int>(n, 0));
        int left = 0, right = n-1, up = 0, down = n-1;
        int index = 1;
        while(index <= n*n){
            for(int i = left; i <= right; ++i)
                matrix[up][i] = index++;  // 1->2->3  9
            ++up;
            for(int i = up; i <= down; ++i)
                matrix[i][right] = index++;  // 4->5
            --right;
            for(int i = right; i >= left; --i)
                matrix[down][i] = index++;   // 6->7
            --down;
            for(int i = down; i >= up; --i)
                matrix[i][left] = index++;  // 8
            ++left;
        }
        return matrix;
    }
};